package com.zbangmall.util.crypt.signature;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;

public class SignatureUtil {

	/**
	 * SHA256withDSA 校验签名
	 * 用公钥对象和签名字符串校验明文
	 *
	 * @param publicKey 公钥对象
	 * @param plaintext 明文字符串
	 * @param signStr   签名字符串
	 * @return
	 */
	public static Boolean verifyBySHA256withDSA(PublicKey publicKey, String signStr, String plaintext) {
		try {
			//【1】准备签名对象
			Signature signature = Signature.getInstance("SHA256withRSA");
			signature.initVerify(publicKey);
			signature.update(plaintext.getBytes());

			//【2】开始校验签名
			byte[] decodeBytes = Base64.getDecoder().decode(signStr.getBytes());
			return signature.verify(decodeBytes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * SHA256withDSA 签名
	 *
	 * @param privateKey 私钥对象
	 * @param str        待签名的字符串
	 * @return 签名字符串
	 */
	public static String signBySHA256withDSA(PrivateKey privateKey, String str) {
		try {
			//【1】准备签名对象
			Signature signature = Signature.getInstance("SHA256withRSA");
			signature.initSign(privateKey);
			signature.update(str.getBytes());

			//【2】开始签名
			byte[] signBytes = signature.sign();

			return Base64.getEncoder().encodeToString(signBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
